/**
 * 创建聊天
 */
var CHATFORM = "<div class='modal' id='chat-dialog' tabindex='-1' role='dialog' aria-hidden='true'>"
		+ "<div class='modal-dialog'>"
		+ "<div class='modal-content'>"
		+ "<div class='modal-header'>"
		+ "<button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>"
		+ "<h4 class='modal-title' id='dialog-title'><span class='glyphicon glyphicon-edit'></span> yanhao</h4>"
		+ "</div>"
		+ "<div class='modal-body'>"
		+ "<div class='form-group'>"
		+ "<textarea rows='14' class='form-control'></textarea>"
		+ "</div>"
		+ "<div class='form-group'>"
		+ "<input type='text' name='message' class='form-control'/>"
		+ "</div>"
		+ "</div>"
		+ "<div class='modal-footer'>"
		+ "<button class='btn btn-primary sendMsg'>确认</button>"
		+ "</div>"
		+ "</div>" + "</div>" + "</div>";

$.extend({
	JSONTOSTRING: function(obj){
        switch(typeof(obj)){   
            case 'string':   
                return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';   
            case 'array':   
                return '[' + obj.map($.JSONTOSTRING).join(',') + ']';   
            case 'object':   
                 if(obj instanceof Array){   
                    var strArr = [];   
                    var len = obj.length;   
                    for(var i=0; i<len; i++){   
                        strArr.push($.JSONTOSTRING(obj[i]));   
                    }   
                    return '[' + strArr.join(',') + ']';   
                }else if(obj==null){   
                    return 'null';   
  
                }else{   
                    var string = [];   
                    for (var property in obj) string.push($.JSONTOSTRING(property) + ':' + $.JSONTOSTRING(obj[property]));   
                    return '{' + string.join(',') + '}';   
                }   
            case 'number':   
                return obj;   
            case false:   
                return obj;   
        }   
	},
	STRINGTOJSON: function(obj){
		return eval('(' + obj + ')');
	},
	IMSTORAGE : {
		remove: function(key){
			if(window.localStorage.getItem(key) != null)
				window.localStorage.removeItem(key);
			else
				document.cookie = key + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
			
		},
		get : function(key) {
			if (window.localStorage.getItem(key) != null)
				return window.localStorage.getItem(key);
			else {
				var arr = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
				return (arr != null)?unescape(arr[2]):null;
			}
		},
		put : function(key, value) {
			if (window.localStorage) 
				window.localStorage.setItem(key, value);
			else {
				var exp = new Date();
				exp.setTime(exp.getTime() + 1 * 24 * 60 * 60 * 1000);
				document.cookie = key + "=" + escape(value) + ";expires=" + exp.toGMTString();
			}
		}
	},
	IMAJAX : function(params, successFun, errFun) {
		$.ajax({
			url : "/admin/message/save",
			type : "POST",
			dataType : 'json',
			data : params,
			success : successFun,
			error : errFun
		});
	},
	IMFORM : function(roomId, sendFun) {
		$('BODY').append(CHATFORM);

		var CHATDIALOG = $('#chat-dialog').modal('show');
		CHATDIALOG.on('show.bs.modal', function(event) {

		});

		CHATDIALOG.delegate(".sendMsg", "click", function() {
			sendFun('HU', $('input[name="message"]').val(), roomId);
		});

		CHATDIALOG.on('hidden.bs.modal', function(event) {
			$('#chat-dialog').remove();
		});
	},
	/**
	 * .open(openCellBack);
	 * .open(function(){
	 * 		var MESSAGES = $.IMSTORAGE.get("IMPUSH");
	 * 		if(MESSAGES != undefined)
	 * 			console.log(MESSAGES);	
	 * })
	 * .subscribe('IM',subCellBack);
	 * .subscribe('IM',function(data){
	 * 		 console.log(data);
	 * });
	 * .on('message', msgCellBack);
	 * .on('message', function(data){
	 * 		var MESSAGES = $.STRINGTOJSON($.IMSTORAGE.get("IMPUSH"));
	 * 		if(MESSAGES == undefined)
	 * 			MESSAGES = new Array();
	 * 		MESSAGES.push(data);
	 *		$.IMSTORAGE.put("IMPUSH", $.JSONTOSTRING(MESSAGES));
	 * });
	 */
	IMPUSH : function(options) {
		var userId = (options.userId!=undefined)?options.userId:"IM";
		var appId = (options.appId!=undefined)?options.appId:"d9ixqkydqire01ml5fxlrs8r1xsv4xz4f1qxlojkedbic6qr";
		var appKey = (options.appKey!=undefined)?options.appKey:"aklf32g9k9cscd77sowumsm0t447jn79mqkla289efhrdxd5";
		var openCellBack = (options.openCellBack!=undefined)?options.openCellBack:function(data){};
		var subCellBack = (options.subCellBack!=undefined)?options.subCellBack:function(data){};
		var msgCellBack = (options.msgCellBack!=undefined)?options.msgCellBack:function(data){};
		
		var pushObject = AV.push({appId: appId, appKey: appKey})
			.open(openCellBack)
			.subscribe(['IM-' + userId], subCellBack)
			.on('message', msgCellBack);
		
		this.send = function(msgObj, userId, cellback){
			pushObject.send({
				data: msgObj,
				channels: ['IM-' + userId]
			}, cellback);
		}
		
	},
	IMAVCHAT : function(clientId) {
		var params = {
			// appId 需要换成你自己的 appId
			appId : 'd9ixqkydqire01ml5fxlrs8r1xsv4xz4f1qxlojkedbic6qr',
			// clientId 是自定义的名字，当前客户端可以理解的名字
			clientId : clientId,
			// 是否开启 HTML 转义，SDK 层面开启防御 XSS
			encodeHTML : true,
			// auth 是权限校验的方法函数
			// auth: authFun,
			// 是否关闭 WebSocket 的安全链接，即由 wss 协议转为 ws 协议，关闭 SSL 保护
			secure : true
		}

		var map = new Map();

		var rb = AV.realtime(params)
				.on("open", function() {
					$('.chat').each(function() {
						$(this).click(function() {
							var cid = $(this).attr('data-cid');
							rb.room({members : [ cid ], data : { title : cid}},function(rmb) {
								map.put(rmb.id,rmb);
								$.IMFORM(rmb.id, function(friendId, msg, roomId) {
									$.IMAJAX({sender : clientId, message : msg, receiver : friendId },
									function(data, textStatus) {
										map.get(roomId).send({testMsg : msg}, function() {console.log('server ack.');});
									},
									function(XMLHttpRequest, textStatus, errorThrown) {
										window.location.href = "/admin/login";
									});
								});
							});
						});
					});
				}).on('create', function(data) {
					map.get(data.cid).list(function(result) {
						console.log(result);
					});
				}).on('message', function(data) {
					console.log("message");
					console.log(data);
				}).on('join', function(data) {
					var rmb = map.get(data.cid);
					if (rmb == undefined || rmb == null) {
						rb.room(data.cid, function(rmb) {
							map.put(data.cid, rmb)
						});
					}
					rmb.receive(function(data) {// 已经收到的 clientId
						console.log(data);
					});
				}).on('left', function(data) {
					console.log("left = " + data);
				}).on('reuse', function() {
					console.log('正在重新连接。。。');
				});
			}
		});